/*
 * =====================================================================================
 *
 *       Filename:  2C.cpp
 *
 *    Description:  编程珠玑 第二章 问题C
 *
 *        Version:  1.0
 *        Created:  2011-11-14 10:20:27
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (),
 *        Company:
 *
 * =====================================================================================
 */

#include <string>
#include <map>
#include <vector>
#include <fstream>
#include <iterator>
#include <iostream>
#include <algorithm>

//利用散列表处理变位词
class anagram_search
{
    std::map<std::string, std::vector<std::string> > _words;
public:
    void read_and_init(const std::string &name) {
        std::ifstream file(name.c_str());

        std::string word;

        while (file >> word) {
            std::string sign = word;
            std::sort(sign.begin(), sign.end());
            std::vector<std::string> &vt = _words[sign];

            if (vt.end() == std::find(vt.begin(), vt.end(), word)) {
                vt.push_back(word);
            }
        }
    }

    std::vector<std::string> &find_words(const std::string &word) {
        std::string sign = word;
        std::sort(sign.begin(), sign.end());
        return _words[sign];
    }
};

int main(int argc, char *argv[])
{
    anagram_search as;
    as.read_and_init("longmandic.txt");

    std::cout << "please input any word, and I will find the anagrams of it.\n";

    std::string word;

    while (std::cin >> word) {
        if (word == "q" || word == "Q") {
            break;
        } else {
            std::vector<std::string> &fd = as.find_words(word);
            std::copy(fd.begin(), fd.end(), std::ostream_iterator<std::string>(std::cout, " "));
            std::cout << std::endl;
        }
    }

    return 0;
}
